package cn.jsj.onclock.controller;

import cn.jsj.onclock.interceptor.swich.PassToken;
import cn.jsj.onclock.pojo.UserEnt;
import cn.jsj.onclock.pojo.identity.UserIdentityEnum;
import cn.jsj.onclock.result.Result;
import cn.jsj.onclock.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

import java.sql.ResultSet;

import static cn.jsj.onclock.interceptor.RequestThreadContext.requesterIdentity;
import static cn.jsj.onclock.interceptor.RequestThreadContext.requesterUserId;

/**
 * @author 卢斌
 */
@Controller
@CrossOrigin
@ResponseBody
@RequestMapping(value = "/user")
public class UserController {

    private final UserService userService;


    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户登录与注册
     */
    @PassToken
    @GetMapping(value = "/login", params = {"code"})
    public Result<String> userLogin(@RequestParam("code") String code) {
        String token = userService.userLogin(code);
        return Result.success(token);
    }


    /**
     * 获取用户个人基本信息
     */
    @GetMapping(value = "/user_info")
    public Result<UserEnt> userInfo() {
        Long userId = requesterUserId();
        UserEnt userEnt = userService.getUserInfo(userId);
        return Result.success(userEnt);
    }


    /**
     * 更新用户个人信息
     */
    @PutMapping(value = "/user_info")
    public Result<Object> updateUser(@RequestBody UserEnt userEnt) {
        Long userId = requesterUserId();
        userEnt.setId(userId);
        userService.updateUserInformation(userId, userEnt.getName(), userEnt.getTeleNumber(), userEnt.getOrgName());
        return Result.success();
    }


    /**
     * 用户更换头像
     */
    @PostMapping(value = "/head_picture")
    public Result<Object> uploadHeadPicture(@RequestParam("picture") MultipartFile pictureFile) {
        Long userId = requesterUserId();
        userService.saveUserHeadPicture(userId, pictureFile);
        return Result.success();
    }


    /**
     * 获取用户上传的头像
     */
    @GetMapping(value = "/head_picture", params = {"userId"})
    public void checkoutUserHeadPicture(@RequestParam("userId") Long userId, HttpServletResponse response) {
        userService.getUserHeadPicture(userId, response);
    }


    /**
     * 超管用户登录的安全码
     */
    @GetMapping(value = "/security_code")
    public Result<Integer> getSuperAdminSecurityCode() {
        Long userId = requesterUserId();
        UserIdentityEnum identity = requesterIdentity();
        Integer code = userService.createSuperAdminLoginSecurityCode(userId, identity);
        return Result.success(code);
    }


}
